//
//  PlayerController.m
//  视频测试
//
//  Created by zxy on 2018/12/29.
//  Copyright © 2018 zxy. All rights reserved.
//

#import "PlayerController.h"
#import <ZFPlayer/ZFPlayer.h>
#import <ZFPlayer/ZFPlayerControlView.h>
#import <ZFPlayer/ZFAVPlayerManager.h>
#import "ZFUtilities.h"
#import <UIImageView+ZFCache.h>
#import "ZFOtherCell.h"
#import "ZFTableHeaderView.h"
#import "BANetManager/BANetManager.h"
#import "BANetManager/BADataEntity.h"
@interface PlayerController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) ZFPlayerController *player;
@property (nonatomic, strong) ZFPlayerControlView *controlView;
@property (nonatomic, strong) ZFTableHeaderView *headerView;
@property (nonatomic, strong) NSArray <NSURL *>*assetURLs;//视频播放URL
@property (nonatomic, strong) UITableView *tableView;
@property(nonatomic,strong)UIButton *downLoadBtn;
@end

static NSString *kIdentifier = @"kIdentifier";
//视频播放地址
static NSString *video_url = @"http://e.chngsl.com/11.mp4";

//视频播放器封面
static NSString *kVideoCover = @"https://upload-images.jianshu.io/upload_images/635942-14593722fe3f0695.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240";
@implementation PlayerController

-(UIButton *)downLoadBtn{
    if(!_downLoadBtn){
        _downLoadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_downLoadBtn setImage:[UIImage imageNamed:@"download"] forState:UIControlStateNormal];
        _downLoadBtn.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 30, 10, 20, 22);
        [_downLoadBtn addTarget:self action:@selector(down) forControlEvents:UIControlEventTouchUpInside];
    }
    return _downLoadBtn;
}

- (ZFTableHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[ZFTableHeaderView alloc] init];
       
        @weakify(self)
        _headerView.playCallback = ^{
            @strongify(self)
              [self.controlView.portraitControlView addSubview:self.downLoadBtn];
            self.player.currentPlayerManager.assetURL = [NSURL URLWithString:video_url];
            [self.controlView showTitle:@"星河司歌" coverURLString:kVideoCover fullScreenMode:ZFFullScreenModeLandscape];
        };
    }
    return _headerView;
}

#pragma mark - getter

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        [_tableView registerClass:[ZFOtherCell class] forCellReuseIdentifier:kIdentifier];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.rowHeight = 100;
    }
    return _tableView;
}

- (ZFPlayerControlView *)controlView {
    if (!_controlView) {
        _controlView = [ZFPlayerControlView new];
        /// 快进视图是否显示动画，默认NO。
        _controlView.fastViewAnimated = YES;
    }
    return _controlView;
}




- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"星河集团司歌";
    [self.view addSubview:self.tableView];

    self.tableView.tableHeaderView = self.headerView;
    self.headerView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width*9/16);
    
    /// playerManager
    ZFAVPlayerManager *playerManager = [[ZFAVPlayerManager alloc] init];
    /// player的tag值必须在cell里设置
    self.player = [ZFPlayerController playerWithPlayerManager:playerManager containerView:self.headerView.coverImageView];
    self.player.controlView = self.controlView;
    @weakify(self)
    self.player.orientationWillChange = ^(ZFPlayerController * _Nonnull player, BOOL isFullScreen) {
        @strongify(self)
        [self setNeedsStatusBarAppearanceUpdate];
        [UIViewController attemptRotationToDeviceOrientation];
        self.tableView.scrollsToTop = !isFullScreen;
        if(isFullScreen){//横屏
             self.downLoadBtn.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 30, 10, 20, 22);
             [self.controlView.landScapeControlView addSubview:self.downLoadBtn];
        }else{//竖屏
             self.downLoadBtn.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 30, 10, 20, 22);
             [self.controlView.portraitControlView addSubview:self.downLoadBtn];
        }
    };
    
    self.player.playerDidToEnd = ^(id  _Nonnull asset) {
        @strongify(self)
        [self.player stopCurrentPlayingCell];
        [self.player stop];
    };
    
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.player.viewControllerDisappear = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.player.viewControllerDisappear = YES;
}

//布局控制器页面子控件
- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    CGFloat y1 = CGRectGetMaxY(self.navigationController.navigationBar.frame);
    CGFloat h1 = CGRectGetMaxY(self.view.frame);
    self.tableView.frame = CGRectMake(0, y1, self.view.frame.size.width, h1-y1);
    
}


- (void)playClick:(UIButton *)sender {
    [self.player playTheIndex:0];
    [self.controlView showTitle:@"星河司歌" coverURLString:kVideoCover fullScreenMode:ZFFullScreenModeLandscape];
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
    return UIStatusBarAnimationSlide;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    if (self.player.isFullScreen) {
        return UIStatusBarStyleLightContent;
    }
    return UIStatusBarStyleDefault;
}

- (BOOL)prefersStatusBarHidden {
    return self.player.isStatusBarHidden;
}

- (BOOL)shouldAutorotate {
    return self.player.shouldAutorotate;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    if (self.player.isFullScreen) {
        return UIInterfaceOrientationMaskLandscape;
    }
    return UIInterfaceOrientationMaskPortrait;
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZFOtherCell *cell = [tableView dequeueReusableCellWithIdentifier:kIdentifier];
    return cell;
}
//下载视频
-(void)down{
 
    //视频保存路径
    NSString *fileCachePath = [NSHomeDirectory() stringByAppendingString:[NSString stringWithFormat:@"/Library/Caches/companySong.mp4"]];
    if([self isFileExist:@"companySong.mp4"]){
        NSLog(@"缓存文件已经存在");
        if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(fileCachePath)) {
            //保存相册核心代码
            UISaveVideoAtPathToSavedPhotosAlbum(fileCachePath, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
        }
        return;
    }
    
    BAFileDataEntity *fileEntity = [BAFileDataEntity new];
    fileEntity.urlString = video_url;
    fileEntity.filePath = fileCachePath;
    
    [BANetManager ba_downLoadFileWithEntity:fileEntity successBlock:^(id response) {
        if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(response)) {
            //保存相册核心代码
            UISaveVideoAtPathToSavedPhotosAlbum(response, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
        }
    } failureBlock:^(NSError *error) {
        
    } progressBlock:^(int64_t bytesProgress, int64_t totalBytesProgress) {
        /*! 封装方法里已经回到主线程，所有这里不用再调主线程了 */
        CGFloat progress = 100 * bytesProgress/totalBytesProgress;
       NSLog(@"%f",progress);
   }];

}
#pragma mark 视频保存完毕的回调
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (error) {
        NSLog(@"保存视频过程中发生错误，错误信息:%@",error.localizedDescription);
    }else{
        NSLog(@"视频保存成功.");
    }
}


//判断文件是否已经在沙盒中已经存在？
-(BOOL)isFileExist:(NSString *)fileName
{
    NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    NSString *filePath = [path stringByAppendingPathComponent:fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager fileExistsAtPath:filePath];
    return result;
}
@end
